<?php
	include('includes/start_session.php');
	include('db-api/txt-db-api.php');
	include('includes/login_required.php');
	
	if(isset($_GET['action']) && $_GET['action'] == 'add' && isset($_POST['courses']))
	{
		$db = new Database('Eclass');
	
		$checks = $_POST['courses'];
		
		$any_chosen = false;
		$query = '';
		foreach($checks as $check)
		{
			$any_chosen = true;
			if($query == '')
				$query = ' AND (CourseId = ' . $check;
			else
				$query .= ' OR CourseId = ' . $check;
		}
		$query .= ')';
		if($any_chosen == false)
			header('Location: user_announcements.php?message=1');
		else
		{
			$db->executeQuery('UPDATE UsersCourses SET ReceiveMail = \'true\' WHERE ' .
				'UserName = \'' . $_SESSION['username'] . '\'' . $query);
			$db->executeQuery('UPDATE ProfessorsCourses SET ReceiveMail = \'true\' WHERE ' .
				'ProfessorName = \'' . $_SESSION['username'] . '\'' . $query);
			header('Location: user_announcements.php?message=2');
		}
	}
	else if(isset($_GET['action']) && $_GET['action'] == 'remove' && isset($_GET['id']))
	{
		$db = new Database('Eclass');
		$rs = $db->executeQuery('SELECT * FROM UsersCourses WHERE UserName = \'' . $_SESSION['username'] .
			'\' AND CourseId = ' . $_GET['id']);
		
		if($rs->next())
		{
			$db->executeQuery('UPDATE UsersCourses SET ReceiveMail = \'false\' WHERE ' .
				'UserName = \'' . $_SESSION['username'] . '\' AND CourseId = ' . $_GET['id']);
			header('Location: user_announcements.php?message=2');
		}
		else
		{
			$rs = $db->executeQuery('SELECT * FROM ProfessorsCourses WHERE ProfessorName = \'' . $_SESSION['username'] .
				'\' AND CourseId = ' . $_GET['id']);
		
			if($rs->next())
			{
				$db->executeQuery('UPDATE ProfessorsCourses SET ReceiveMail = \'false\' WHERE ' .
					'ProfessorName = \'' . $_SESSION['username'] . '\' AND CourseId = ' . $_GET['id']);
				header('Location: user_announcements.php?message=2');
			}
			else
				header('Location: user_announcements.php?message=3');
		}
	}
	else
		header('Location: user_announcements.php?message=1');
?>